import React, {Component} from 'react';
import {connect} from 'dva';
import {Form, FormItem, Input, Select, Button, Upload, Icon, message, Modal, Radio, DatePicker} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import {EditorState, convertToRaw, ContentState} from 'draft-js';
import {Editor} from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import styles from './Add.less';
import moment from 'moment/moment';
import request from '@/utils/request';
import {IMG_URL} from '../../utils/utils';
import E from 'wangeditor'
export default @connect(({active, loading}) => ({
  active,
  loading: loading.effects['active/fetchCategory'],
  submitting: loading.effects['active/save'],
}))

@Form.create()
class ActiveAdd extends Component {
  state = {
    editorState: "",
    preview: '',
    visible: false,
    imageList: [],
    categoryList: [],
    article_type:"活动预告"
  };

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'active/fetchCategory',
      payload: {type: 'activity'},
    });
    const elem = this.refs.editorElem
    const editor = new E(elem)
    editor.customConfig.onchange = html => {
      this.setState({
        editorContent: html
      })
    }
    editor.customConfig.customUploadImg = function (files, insert) {
      console.log(files.length)
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        let timestamp3 = new Date().getTime();
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name', timestamp3 + "" + files[0].name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${files[0].name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', files[0]);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          if (xhr.responseText.indexOf("Error") != -1) {
            alert(xhr.responseText.indexOf("Error"))
          } else {
            const response = JSON.parse(xhr.responseText);
            if (response.filename) {
              insert(IMG_URL + response.filename)
            } else {
              alert('服务器异常');
            }
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法

      // 上传代码返回结果之后，将图片插入到编辑器中

    }
    editor.customConfig.zIndex = 1
    editor.create()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.active.categoryList.length > 0) {
      this.setState({categoryList: nextProps.active.categoryList});
    }
  };
  addArticle = () => {
    const {dispatch, form} = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'active/save',
          payload: {
            article_pic: this.state.imageList.length == 0 ? "" : this.state.imageList[0].url,
            article_detail: this.state.editorContent, ...values,
            article_activityStartTime: values.article_activityStartTime && moment(values.article_activityStartTime).format("YYYY-MM-DD HH:mm:ss"),
            article_activityEndTime: values.article_activityEndTime && moment(values.article_activityEndTime).format("YYYY-MM-DD HH:mm:ss"),
            article_activityDownTime: values.article_activityDownTime && moment(values.article_activityDownTime).format("YYYY-MM-DD HH:mm:ss"),
            article_activityHoldTime: values.article_activityHoldTime && moment(values.article_activityHoldTime).format("YYYY-MM-DD HH:mm:ss"),
          },
        });
      }
    });
  };
  beforeUpload = file => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name', file.name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${file.name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', file);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          const response = JSON.parse(xhr.responseText);
          if (response.filename) {
            this.setState(({imageList}) => ({
              imageList: [{
                uid: file.uid,
                name: file.name,
                status: file.status,
                type: file.type,
                result: file.name,
                url: IMG_URL + response.filename,
              }],
            }));
          } else {
            alert('服务器异常');
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
    };
    return false;
  };

  handlePreview = (file) => {
    this.setState({
      preview: file.url || file.thumbUrl,
      visible: true,
    });
  };
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  }
  onChangeType=(e)=>{
    console.log( e.target.value);
    this.setState({
      article_type: e.target.value,
    });
  }
  render() {
    const propsImgs = {
      onRemove: (file) => {
        this.setState(({imageList}) => {
          const index = imageList.indexOf(file);
          const newFileList = imageList.slice();
          newFileList.splice(index, 1);
          return {imageList: newFileList};
        });
      },
      beforeUpload: this.beforeUpload,
      fileList: this.state.imageList,
      onPreview: this.handlePreview,
      accept: 'image/*',
      listType: 'picture-card',
    };
    const {editorState} = this.state;
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };
    const {
      form: {getFieldDecorator, getFieldValue},
    } = this.props;
    // const categoryOption=
    const {preview, visible, imageList} = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <PageHeaderWrapper
        title="新增活动"
      >
        <Form onSubmit={this.handleSubmit} hideRequiredMark style={{marginTop: 8}}>
          <Form.Item {...formItemLayout} label="活动type">
            {getFieldDecorator('article_type', {
              initialValue: this.state.article_type,
              rules: [
                {
                  required: true,
                  message: '活动type',
                },
              ],
            })(<Radio.Group onChange={this.onChangeType}>
              <Radio value="活动预告">活动预告</Radio>
              <Radio value="活动回顾">活动回顾</Radio>
            </Radio.Group>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="标题">
            {getFieldDecorator('article_title', {
              rules: [
                {
                  required: true,
                  message: '标题不能为空',
                },
              ],
            })(<Input placeholder="请输入标题"/>)}
          </Form.Item>
          {
            this.state.article_type == "活动预告" && <div>
              <Form.Item {...formItemLayout} label="主讲人">
                {getFieldDecorator('article_speaker', {
                  rules: [
                    {
                      required: true,
                      message: '主讲人不能为空',
                    },
                  ],
                })(<Input placeholder="请输入主讲人"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="报名金额">
                {getFieldDecorator('article_attendPrice')(<Input placeholder="请输入报名金额"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="报名数">
                {getFieldDecorator('article_maxAttendCount')(<Input placeholder="请输入报名数"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="关联文章">
                {getFieldDecorator('relatedActivity')(<Input placeholder="请输入报名数"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动类别">
                {getFieldDecorator('article_category', {
                  rules: [
                    {
                      required: true,
                      message: '请选择活动类别',
                    },
                  ],
                })(<Select>
                  {this.state.categoryList.map(category => <Select.Option value={category.name}
                                                                          key={category.categoryId}>{category.name}</Select.Option>)}
                </Select>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动开始时间">
                {getFieldDecorator('article_activityStartTime')(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动开始时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动举行时间">
                {getFieldDecorator('article_activityHoldTime')(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动举行时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动结束时间">
                {getFieldDecorator('article_activityEndTime')(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动结束时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动下线时间">
                {getFieldDecorator('article_activityDownTime')(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动下线时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动标签">
                {getFieldDecorator('article_tag', {
                  rules: [
                    {
                      required: true,
                      message: '活动标签不能为空',
                    },
                  ],
                })(<Input placeholder="多个，中文逗号隔开"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="地点">
                {getFieldDecorator('article_address', {
                  rules: [
                    {
                      required: true,
                      message: '活动地点',
                    },
                  ],
                })(<Input placeholder="活动地点不能为空"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动摘要">
                {getFieldDecorator('article_describe', {
                  rules: [
                    {
                      required: true,
                      message: '活动摘要不能为空',
                    },
                  ],
                })(
                  <Input.TextArea
                    style={{minHeight: 32}}
                    placeholder="请输入活动摘要"
                    rows={4}
                  />,
                )}
              </Form.Item>
            </div>
          }
          <Form.Item {...formItemLayout} label="封面图">
            <div>
              <Upload {...propsImgs}>
                {
                  imageList.length >= 1 ? null : uploadButton
                }
              </Upload>
              <Modal visible={visible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{width: '100%'}} src={preview}/>
              </Modal>
            </div>
          </Form.Item>
        </Form>
        <div ref="editorElem" style={{textAlign: 'left'}}>
        </div>
        <FooterToolbar style={{width: '100%'}}>
          <Button type="primary" onClick={() => this.addArticle()}>
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}
